package network;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import javax.sound.sampled.AudioFormat;
import javax.swing.JOptionPane;

import controller.Controller;
import controller.Outils;

import model.AudioFormatWrapper;
import model.Call;
import model.Model;
import model.Signal;
import model.EnumSignalType;

public class TCPCaller extends Thread {

	private Socket socketCaller;
	private InetAddress ipEnFace;
	private int portTCPenFace;
	private Call call;
	private Controller controller;
	private Model model;
	private AudioFormatWrapper audioToBeUse;


	
		public TCPCaller(InetAddress  ipEnFace, int portTCPenFace,Controller controller,AudioFormatWrapper audioImGonnaUse) {
			this.ipEnFace = ipEnFace;
			this.portTCPenFace = portTCPenFace;
			this.call = call;
			this.controller = controller;
			this.model=controller.getModel();
			this.audioToBeUse=audioImGonnaUse;
			call = new Call();
			this.model.addCall(call);
	}

		public void run(){
	
			try {
				socketCaller = new Socket(ipEnFace,portTCPenFace);
				TCPService tcpService = new TCPService(call, socketCaller, "TCPServiceDuCaller",controller);
				tcpService.start();
				
				call.initCallForSendRequest(ipEnFace, portTCPenFace, tcpService, this.model.getFifo().poll(), audioToBeUse.getAudioFormat());
				this.controller.getView().refreshAll();
				//construire le signal de demande d'appel et l'envoyer grâce à treadservice
				Signal signalCallRequest = new Signal();
				signalCallRequest.factorySignalCallRequest(call.getLocalUdpPort(), audioToBeUse, this.model.getProperties().getProperty("firstname"), this.model.getProperties().getProperty("lastname"));
				tcpService.sendSignal(signalCallRequest);
			} catch (IOException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null,
						"network problem", "Information",
						JOptionPane.INFORMATION_MESSAGE);
			}
			
			
			
			
		}
	
	
	
	
}
